package com.cscec5b.inspection.controller;

import com.cscec5b.inspection.dto.ManualFormDTO;
import com.cscec5b.inspection.dto.ManualFormSubmitDTO;
import com.cscec5b.inspection.dto.TaskListItem;
import com.cscec5b.inspection.entity.Task;
import com.cscec5b.inspection.service.TaskService;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * TaskController
 * 与“任务”相关的接口：
 *  - GET  /api/tasks                              任务列表
 *  - GET  /api/tasks/{id}/fill/manual/schema      手动填报 Schema（动态表单）
 *  - POST /api/tasks/{id}/fill/manual             手动填报 保存
 */
@RestController
@RequestMapping("/api/tasks")
public class TaskListController {

    private final TaskService service;

    public TaskListController(TaskService service) {
        this.service = service;
    }

    /**
     * 列表接口（无 Spring Security 版）
     * - userId：可来自 query 参数 ?userId=xxx，或请求头 X-User-Id；都缺省则默认 1
     * - status：todo | done | (null=全部)
     * - keyword：模糊查询（项目名/部位/类型）
     * - page/size：分页
     */
    @GetMapping
    public Map<String, Object> list(
            @RequestParam(defaultValue = "todo") String state, // todo | done
            @RequestParam(required = false) Long projectId,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            jakarta.servlet.http.HttpSession session

    ) {

//        long userId = 1L; // TODO: 从登录上下文取真实 userId
        Object userId = session.getAttribute("USER_CODE");
        if (userId == null) throw new RuntimeException("未登录或会话失效");
//        return projectService.listByUserCode(String.valueOf(val));
        return service.list(Long.parseLong(String.valueOf(userId)), state, projectId, keyword, page, size);
    }

    /**
     * 可选：最简详情（若前端需要）
     * 这里演示直接从列表里取；生产建议做单独的 Service/Repository 查询
     */
    @GetMapping("/{id}")
    public Map<String, Object> detail(
            @PathVariable Long id,
            @RequestParam(required = false) Long userId,
            @RequestHeader(value = "X-User-Id", required = false) Long userIdHeader
    ) {
        Long uid = userId != null ? userId : (userIdHeader != null ? userIdHeader : 1L);
        Page<Task> p = service.listForUser(uid, null, null, 1, 1);
        return p.getContent().stream()
                .filter(t -> Objects.equals(t.getId(), id))
                .findFirst()
                .map(t -> {
                    Map<String, Object> m = new HashMap<>();
                    m.put("id", t.getId());
                    m.put("projectName", t.getProject().getName());
                    m.put("taskName", (t.getLocation() == null ? "" : t.getLocation()) + " - " + (t.getType() == null ? "任务" : t.getType()));
                    m.put("startTime", t.getStartTime());
                    m.put("deadline", t.getDeadline());
                    m.put("state", t.getState().name());      // TODO/DONE
                    m.put("stateText", t.getState() == Task.State.DONE ? "已办" : "待办");
                    return m;
                })
                .orElseGet(Collections::emptyMap);
    }



    // ===== 手动填报 Schema（推荐路径） =====
    @GetMapping("/{id}/manual-form")
    public ManualFormDTO manualSchema(@PathVariable("id") long taskId, jakarta.servlet.http.HttpSession session) {
        Object userId = session.getAttribute("USER_CODE");
        if (userId == null) throw new RuntimeException("未登录或会话失效");
        return service.loadManualForm(taskId, Long.parseLong(String.valueOf(userId))); // ← 改为带 userId 的重载
    }
//    // 兼容旧路径：/fill/manual/schema
//    @GetMapping("/{id}/fill/manual/schema")
//    public ManualFormDTO manualSchemaLegacy(@PathVariable("id") long taskId){
//        return service.loadManualForm(taskId);
//    }

    // ===== 手动填报 保存（推荐路径） =====
    @PostMapping("/{id}/manual-form")
    public Map<String,Object> manualSave(@PathVariable("id") long taskId,
                                         @RequestParam("taskType") String taskType,
                                         @RequestBody ManualFormSubmitDTO body){
        service.saveManualForm(taskId, taskType, body);
        return Map.of("ok", true);
    }
    // 兼容旧路径
    @PostMapping("/{id}/fill/manual")
    public Map<String,Object> manualSaveLegacy(@PathVariable("id") long taskId,
                                               @RequestParam("taskType") String taskType,
                                               @RequestBody ManualFormSubmitDTO body){
        service.saveManualForm(taskId, taskType, body);
        return Map.of("ok", true);
    }
}
